package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.hmall.common.clients.ItemClient;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import com.hmall.search.pojo.ItemDOC;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.SearchService;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    public ItemClient itemClient;

    @Override
    public List<String> suggestion(String key) {
        try {
            //1.准备request
            SearchRequest request = new SearchRequest("hmall");
            //2.DSL
            request.source().suggest(new SuggestBuilder()
                    .addSuggestion(
                            "mySuggestion",
                            SuggestBuilders
                                    .completionSuggestion("suggestion")
                                    .prefix(key)
                                    .skipDuplicates(true)
                                    .size(10)
                    )
            );
            //3.发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //4.解析结果
            Suggest suggest = response.getSuggest();
            //根据补全查询名称，获取补全结果
            CompletionSuggestion mySuggestion = suggest.getSuggestion("mySuggestion");
            List<String> list = new ArrayList<>();
            //获取option并遍历
            for (CompletionSuggestion.Entry.Option option : mySuggestion.getOptions()) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        try {
            //1.准备request
            SearchRequest request = new SearchRequest("hmall");
            //2.DSL
            //2.1.query
            buildBasicQuery(request, params);
            //2.2.size
            request.source().size(0);
            //聚合
            buildAggregation(request);
            //3.发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //4.解析结果
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            List<String> brandAggs = getAggName(aggregations, "brandAgg");
            List<String> categoryAggs = getAggName(aggregations, "categoryAgg");
            result.put("brand", brandAggs);
            result.put("category", categoryAggs);
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private List<String> getAggName(Aggregations aggregations, String aggName) {
        //根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        //获取bucket
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        //遍历并获取key
        List<String> keyList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            keyList.add(bucket.getKeyAsString());
        }
        return keyList;
    }

    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(100)
        );


    }

    @Override
    public PageDTO<ItemDOC> list(RequestParams params) {
        try {
            //1.准备request
            SearchRequest request = new SearchRequest("hmall");
            //2.DSL
            //2.1.query
            buildBasicQuery(request, params);
            if (!params.getSortBy().equals("default")) {
                request.source().sort(params.getSortBy(), SortOrder.DESC);
            }
            //2.2.分页
            int page = params.getPage();
            int size = params.getSize();
            request.source().from((page - 1) * size).size(size);

            //3.发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //4.解析结果
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void save(Long id) {
        try {
            Item item = itemClient.getById(id);
            if (item == null) {
                return;
            }
            ItemDOC itemDOC = new ItemDOC(item);

            //1.准备request
            IndexRequest request = new IndexRequest("hmall").id(id.toString());
            String s = JSON.toJSONString(itemDOC);
            //2.DSL
            request.source(s, XContentType.JSON);
            //3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(Long id) {
        try {
            //1.准备request
            DeleteRequest request = new DeleteRequest("hmall", id.toString());
            //2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private PageDTO<ItemDOC> handleResponse(SearchResponse response) {
        //响应解析
        SearchHits searchHits = response.getHits();
        //总条数
        long total = searchHits.getTotalHits().value;
        //文档数组
        SearchHit[] hits = searchHits.getHits();
        //遍历
        List<ItemDOC> items = new ArrayList<>();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            ItemDOC itemDOC = JSON.parseObject(json, ItemDOC.class);
            //获取高亮
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)) {
                //根据字段名获取高亮结果
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField != null) {
                    //获取高亮值
                    String name = highlightField.getFragments()[0].string();
                    itemDOC.setName(name);
                }
            }
            items.add(itemDOC);
        }
        return new PageDTO<ItemDOC>(total, items);
    }

    private void buildBasicQuery(SearchRequest request, RequestParams params) {
        //bool查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //关键字搜索
        String key = params.getKey();
        if (StringUtils.isEmpty(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        //分类
        String category = params.getCategory();
        if (!StringUtils.isEmpty(category)) {
            boolQuery.filter(QueryBuilders.termQuery("category", category));
        }
        //品牌
        String brand = params.getBrand();
        if (!StringUtils.isEmpty(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand", brand));
        }
        //价格
        Integer minPrice = params.getMinPrice();
        Integer maxPrice = params.getMaxPrice();
        if (minPrice != null && maxPrice != null) {
            boolQuery.filter(QueryBuilders
                    .rangeQuery("price")
                    .lte(maxPrice * 100)
                    .gte(minPrice * 100));
        }
        //算分控制
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                boolQuery,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(10))});
        //放入source
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
        request.source().query(functionScoreQuery);
    }
}
